<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>依赖注入 - <button @click="count++">btn</button></h2>
      <!-- 跨组件传参 -->
      <child1></child1>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      // 如果希望依赖注入有响应式，需要从Vue去解构computed
      const { createApp, computed } = Vue;

      const Child2 = {
        data() {
          return {
            num: 123,
          };
        },
        // 子组件加注入, 数组语法
        // inject: ["count", "fn"],

        // 对象
        inject: {
          count2: {
            // default表示默认值
            default: 9,
            // from表示重新取名
            from: "count",
          },
        },
        template: `
          <div>child2组件 - {{ count2 }}</div>
          <button @click="fn(this.num)">fn</button>
        `,
      };

      const Child1 = {
        template: `
          <div>child1组件</div>
          <child2></child2>
        `,
        components: {
          Child2,
        },
      };

      const app = createApp({
        data() {
          return {
            count: 10,
          };
        },
        methods: {
          fn(n) {
            console.log("fn", n);
          },
        },
        components: {
          Child1,
        },
        // 父组件加依赖
        provide() {
          return {
            // count: this.count,
            count: computed(() => this.count),
            fn: this.fn,
          };
        },
      });

      // 去除警告
      app.config.unwrapInjectedRef = true;

      app.mount("#app");
    </script>
  </body>
</html>
